import storm.locals as sls
import sqlite3 as sqlite
import numpy as np
import matplotlib.pyplot as plt
import zlib

DBName = 'test.sqlite'
DBScheme = 'db_scheme.sql'

class Data(object):
  __storm_table__ = "data"
  name = sls.Unicode(primary=True)
  information = sls.Unicode()
  datum = sls.RawStr()
  # Defining Properties as the datum should be stored compressed
  # ------------------------------------------------------------
  def nice_datum():
    def fget(self):
      return np.loads(zlib.decompress(self.datum))
    def fset(self, value):
      try:
        self.datum = zlib.compress(value.dumps(), 9)
      except Exception, e:
        print "Something went wrong - message: %s" %(e)
    return locals()
  nice_datum = property(**nice_datum())

def db_create(db_name, db_schema):
  file = open(db_schema, 'r')
  sql = "".join(file.readlines())
  cxn = sqlite.connect(db_name)
  cursor = cxn.cursor()
  cursor.executescript(sql)
  return cxn, cursor

# Erstellen der Datenbank zum testen
[cxn, cursor] = db_create(DBName, DBScheme)
# here you could play around with SQL-statements:
# cursor.execute(SQLStatement)
cxn.close()

# Zugriff ueber storm
db_target = "test.sqlite"
db = sls.create_database("sqlite:" + db_target)
store = sls.Store(db)

test = Data()
test.name = u"test3"
test.information = u"lalala"
test.nice_datum = np.linspace(-10,10)**2

store.add(test)
store.commit()

mytest = store.find(Data, Data.name == u'test3').one()
plt.plot(mytest.nice_datum)
plt.show()

# erase test.sqlite
